package com.xiaoke.api.controller;

import com.xiaoke.api.service.CategoryService;
import com.xiaoke.api.service.ShopService;
import com.xiaoke.entity.Category;
import com.xiaoke.entity.Shop;
import com.xiaoke.util.common.AjaxMsg;
import com.xiaoke.util.common.ValidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/catalog/")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ShopService shopService;

    @GetMapping("/index")
    public AjaxMsg index(HttpServletRequest request){
        String appId = request.getHeader("appId");
        Shop shop = shopService.findByAppId(appId);

        List<Category> categoryList = categoryService.findListByShop(shop.getId());
        if(!ValidUtil.isEmpty(categoryList)){
            Category category = categoryList.get(0);
            List<Category> subCategoryList = categoryService.findByParentId(category.getId());
            category.setSubCategoryList(subCategoryList);

            Map res = new HashMap<>();
            res.put("categoryList",categoryList);
            res.put("currentCategory",category);
            return new AjaxMsg(res);
        }
        return new AjaxMsg();
    }

    @GetMapping("/current")
    public AjaxMsg current(Integer id){
        Category category = categoryService.findById(id);
        List<Category> subCategoryList = categoryService.findByParentId(id);
        category.setSubCategoryList(subCategoryList);
        return new AjaxMsg(category);
    }
}
